The .substring() method returns a portion of a string.
public static int loopIt(String str, String x) {
int result = 0;
for (int i = 0; i < str.length(); i++) {
if (str.substring(i, i + 1).equals(x))
result++;
}
return result;
}
Function Call | Return Value | |||
---|---|---|---|---|
loopIt("athenian", "e") | → | |||
loopIt("apples", "a") | → | |||
loopIt("hello", "a") | → | |||
loopIt("alphabet", "h") | → | |||
loopIt("aaaaa", "b") | → |
Experiment with this code on Gitpod.io